package no.group.gowther.rest;

import no.group.gowther.exception.CannotResolveSuchImageTypeException;
import no.group.gowther.service.ImageService;
import no.group.gowther.util.ImageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;

/**
 * @author ayatsuji
 * @date 2022-04-17 22:55
 * @since
 */
@RestController
@RequestMapping("api/image")
public class ImageRestController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageRestController.class);

    @Autowired
    private ImageService imageService;

    @GetMapping
    public void getImage(String imageCode, Integer width, Integer height, HttpServletResponse response) throws IOException {
        final Path image = imageService.decodeImageCode(imageCode);
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(image.toFile()))) {
            if (width != null && height != null) {
                ImageUtils.Dimension imageDimension = ImageUtils.getImageDimension(image.toFile().toPath());
                int newWidth = imageDimension.width() / (imageDimension.height() / height);
                ImageUtils.generateThumbnail(bufferedInputStream, newWidth, height, response.getOutputStream());
                return;
            }
            responseImage(bufferedInputStream, response);
        } catch (CannotResolveSuchImageTypeException e) {
            LOGGER.warn("解析code=[{}]分辨率失败，返回原图", imageCode, e);
            getImage(imageCode, null, null, response);
        }
    }

    private void responseImage(InputStream imageStream, HttpServletResponse response) throws IOException {
        byte[] buffer = new byte[1024 * 1024];
        int len;
        while ((len = imageStream.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, len);
        }
        response.flushBuffer();
    }
}
